package cn.itcast.erp.dao.impl;

import cn.itcast.erp.entity.Dep;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@SuppressWarnings("all")
public class BaseDao<T> extends HibernateDaoSupport {

    private Class<T> entityClass;
    public BaseDao(){
        Type type = getClass().getGenericSuperclass();
        ParameterizedType ptype=(ParameterizedType)type;
        Type[] types = ptype.getActualTypeArguments();
        entityClass = (Class<T>) types[0];
    }

    /**
     * 扩展多条件查询
     *
     */
    public List<T> getListByCondition(T t1,T t2,Object param) {

        DetachedCriteria dc = getDetachedCriteria(t1, t2, param);
        return (List<T>) getHibernateTemplate().findByCriteria(dc);
    }

    /**
     * 分页查询
     * @return
     */
    public List<T> listByPage(T t1, T t2, Object param, int firstResult, int rows) {
        DetachedCriteria dc = getDetachedCriteria(t1, t2, param);
        return (List<T>) getHibernateTemplate().findByCriteria(dc, firstResult, rows);
    }

    /**
     * 统计记录数
     * @param param
     * @return
     */
    public long getCount(T t1, T t2, Object param) {

        DetachedCriteria dc = getDetachedCriteria(t1, t2, param);
        //投影查询 select count(*)
        dc.setProjection(Projections.rowCount());
        List<Long> list = (List<Long>) getHibernateTemplate().findByCriteria(dc);
        return list.get(0);
    }

    /**
     * 增加
     * @param t
     */
    public void add(T t) {
        this.getHibernateTemplate().save(t);
    }

    /**
     * 删除
     * @param id
     */
    public void delete(String id) {

        this.getHibernateTemplate().delete(this.getHibernateTemplate().get(entityClass, id));
    }

    /**
     * 查询实体
     * @param id
     * @return
     */
    public T get(String id) {
        return this.getHibernateTemplate().get(entityClass, id);
    }

    /**
     * 修改
     */
    public void update(T t) {
        this.getHibernateTemplate().update(t);
    }



    /**
     * 构建查询条件
     */
    public DetachedCriteria getDetachedCriteria(T t1, T t2, Object param){
        return null;
    }


}
